<template>
  <div class="app-container">
    <el-form ref="wallpaperForm" :model="wallpaper" label-width="120px" class="el-for-content">

      <el-form-item label="发布者名称">
        <el-input placeholder="" v-model="wallpaper.nickname" style="width: 7%"></el-input>
      </el-form-item>

      <el-form-item label="壁纸类型">
        <el-select v-model="wallpaper.classid" placeholder="please select type">
          <el-option v-for="item in classifyNames" :key="item._id" :label="item.name" :value="`${item._id}`"/>
        </el-select>
      </el-form-item>

      <el-form-item label="壁纸标签">
        <el-input type="text" v-model="wallpaper.tabs"
                  placeholder="壁纸标签，多个标签用逗号隔开"
                  style="width: 50%"
        >
        </el-input>
      </el-form-item>



      <el-form-item label="壁纸描述">
        <el-input type="textarea" v-model="wallpaper.description"
                  placeholder="壁纸描述"
                  style="width: 50%"
                  maxlength="255"
                  show-word-limit
                  :autosize="{ minRows: 3, maxRows: 5}"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="壁纸上传">
        <el-upload
          :action="uploadFileUrl"
          :before-upload="handleBeforeUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :file-list="fileList"
          :limit="1"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过3MB</div>
        </el-upload>

        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button v-show="publishVisible" type="primary" plain @click="publishWallPaper()">上传壁纸</el-button>
        <el-button v-show="editVisible" type="info" plain @click="editWallPaper()">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import { Message } from 'element-ui'

import { addWallPaper, editWallPaper } from '@/api/wallpaper'
import { getClassifyNames } from '@/api/classify'

export default {
  data() {
    return {
      wallpaper: {
        classid: '',
        nickname: '',
        smallPicurl: '',
        tabs: '',
        description: ''
      },
      classifyNames: [], //里面包含id和name字段
      wallpaperClassify: '',
      fileList: [],
      uploadFileUrl: 'http://localhost:8080/api/wallpaper/upload',
      dialogImageUrl: '',
      dialogVisible: false,
      fileType: ['png', 'jpg', 'jpeg'],
      fileSize: 5,
      publishVisible: true,
      editVisible: false
    }
  },
  mounted() {
    //查询所有壁纸分类
    this.getClassifyNames()

    if (this.$route.path === '/wallpaper/publish/edit') {
      console.log(this.$route.query.wallpaper)
      this.wallpaper = this.$route.query.wallpaper
      //只展示修改按钮
      this.editVisible = true
      this.publishVisible = false
      //图片回显->使用数组最是稳健
      this.fileList.push({ name: 'wallpaper', url: this.wallpaper.smallPicurl })
    }
  },

  computed: {},

  watch: {},
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.')
        const fileExt = fileName[fileName.length - 1]
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0
        if (!isTypeOk) {
          Message.warning('文件格式不对')
          return false
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          Message(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },
    // 上传失败
    handleUploadError(err) {
      console.log(err)
      Message.error('上传失败, 请重试！')
    },

    handleUploadSuccess(res, file) {
      console.log(res)
      if (res.code === 200) {
        console.log(res.data)
        this.wallpaper.smallPicurl = res.data
        console.log('上转后图片地址：', this.wallpaper)
      } else {
        Message.error(res.message)
      }
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    publishWallPaper() {
      this.$refs.wallpaperForm.validate((valid) => {
        if (valid) {
          //数组解构
          addWallPaper(this.wallpaper).then((res) => {
            Message.success(res.message)
            this.$router.push('/wallpaper/list')
          }).catch(error => {
            Message.error(error)
            this.$router.push('/wallpaper/list')
          })
        } else {
          Message.warning('表格非法')
        }
      })
    },

    editWallPaper() {
      editWallPaper(this.wallpaper).then(res => {
        Message.success('修改成功')
        this.$router.push('/wallpaper/list')
      })
    },
    getClassifyNames() {
      getClassifyNames().then(response => {
        this.classifyNames = response.data

      }).catch(error => {

      })
    }

  }
}
</script>

<style scoped>
.app-container {
  .el-for-content {
  }
}
</style>
